package com.jt.controller;

import com.jt.service.FileService;
import com.jt.vo.ImageVO;
import com.jt.vo.SysResult;
import org.apache.ibatis.annotations.Options;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@CrossOrigin
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FileService fileService;
    @PostMapping("/upload")
    public SysResult fileUpLoad(MultipartFile file){
        ImageVO imageVO=fileService.upload(file);
        if((imageVO==null)){
            return SysResult.fail();
        }
        return SysResult.success(imageVO);
    }
    /**
     * 完成文件上传案例
     * 类型post
     * 参数:file=字节信息
     * 返回值:SysResult(ImageVO)
     * 知识点:
     *   SpringMVC针对于IO操作开发了MultipartFile
     *   底层实现就是常规IO流,简化了用户的操作过程,无需手动关流
     */

    @DeleteMapping("/deleteFile")
    public SysResult deleteFile(String virtualPath){
        fileService.deleteFile(virtualPath);
        return  SysResult.success();
    }
    public SysResult upload(MultipartFile file) throws IOException {
        //1.获取文件名称  a.jpg
        String fileName = file.getOriginalFilename();
        //2.准备文件目录
        String dir = "D:/project3/images";
        File dirFile = new File(dir);
        if(!dirFile.exists()){//判断目录是否存在
            dirFile.mkdirs(); //创建多级目录
        }
        String path = dir + "/" + fileName;
        //实现文件上传
        file.transferTo(new File(path));
        return SysResult.success();
    }
}
